package com.example.mediaservice;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MediaClient";
    private MediaBrowserCompat mediaBrowser;
    private MediaControllerCompat mediaController;

    // UI 元素
//    private ImageView albumArt;
    private TextView songTitle;
    private TextView songArtist;
    private TextView currentTime;
    private TextView totalTime;
    private TextView lyricsText;
    private android.widget.ScrollView lyricsScrollView;
    private SeekBar progressSeekbar;
    private ImageButton btnPrevious;
    private ImageButton btnPlayPause;
    private ImageButton btnNext;
    private TextView serviceStatus;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private final Handler handler = new Handler();//Handler对象，用于处理Android中的消息和任务
    private LyricManager lyricManager; // 添加歌词管理器
    private final Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            updateProgress();// 更新进度
            handler.postDelayed(this, 1000); // 每秒更新一次
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkAndRequestPermissions();
        initViews();
        setupMediaBrowser();
        setupClickListeners();
        // 初始化歌词管理器
        lyricManager = new LyricManager();
        lyricManager.setOnLyricUpdateListener(this::updateLyricsDisplay);

        Intent serviceIntent = new Intent(this, MediaService.class);
        serviceIntent.setAction("PLAY_MUSIC"); // 可携带播放指令
        startService(serviceIntent); // 启动前台服务
    }
    private void checkAndRequestPermissions() {
//        Toast.makeText(this, "正在检查权限...", Toast.LENGTH_SHORT).show();
        // 在checkAndRequestPermissions方法中添加
        // 根据 Android 版本使用不同的权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                        PERMISSION_REQUEST_CODE);
            }
        } else {
            // Android 12 及以下
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        PERMISSION_REQUEST_CODE);
            }
        }
    }

    private void initViews() {
//        albumArt = findViewById(R.id.album_art);
        songTitle = findViewById(R.id.song_title);
        songArtist = findViewById(R.id.song_artist);
        currentTime = findViewById(R.id.current_time);
        totalTime = findViewById(R.id.total_time);
        lyricsText = findViewById(R.id.lyrics_text);
        progressSeekbar = findViewById(R.id.progress_seekbar);
        btnPrevious = findViewById(R.id.btn_previous);
        btnPlayPause = findViewById(R.id.btn_play_pause);
        btnNext = findViewById(R.id.btn_next);
        serviceStatus = findViewById(R.id.service_status);
        lyricsScrollView = findViewById(R.id.lyrics_scrollview); // 初始化 ScrollView

        // 设置进度条监听器
        progressSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaController != null) {
                    // 用户拖动SeekBar时更新时间显示
                    currentTime.setText(formatTime(progress));
                    //控制媒体播放进度。当用户拖动SeekBar时，seekTo(progress)方法会跳转到指定的播放位置
//                    mediaController.getTransportControls().seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时跳转到指定位置
                if (mediaController != null) {
                    mediaController.getTransportControls().seekTo(seekBar.getProgress());
                }
            }
        });
    }

    // 初始化媒体浏览器连接
    private void setupMediaBrowser() {
        mediaBrowser = new MediaBrowserCompat(
                this,
                new ComponentName(this, MediaService.class),
                connectionCallback,
                null
        );
    }
    // 添加专门的歌词更新方法

    private void setupClickListeners() {
        btnPlayPause.setOnClickListener(v -> {
            if (mediaController != null) {
                PlaybackStateCompat currentState = mediaController.getPlaybackState();
                if (currentState != null) {
                    switch (currentState.getState()) {
                        case PlaybackStateCompat.STATE_PLAYING:
                            mediaController.getTransportControls().pause();
                            break;
                        case PlaybackStateCompat.STATE_PAUSED:
                        case PlaybackStateCompat.STATE_STOPPED:
                            mediaController.getTransportControls().play();
                            break;
                        default:
                            mediaController.getTransportControls().play();
                            break;
                    }
                }
            }
        });

        btnPrevious.setOnClickListener(v -> {
            if (mediaController != null) {
                mediaController.getTransportControls().skipToPrevious();
            }
        });

        btnNext.setOnClickListener(v -> {
            if (mediaController != null) {
                mediaController.getTransportControls().skipToNext();
            }
        });
    }

    private final MediaBrowserCompat.ConnectionCallback connectionCallback =
            new MediaBrowserCompat.ConnectionCallback() {

                @Override
                public void onConnected() {
                    Log.d(TAG, "MediaBrowser connected");
                    try {
                        // 创建 MediaController
                        mediaController = new MediaControllerCompat(
                                MainActivity.this,
                                mediaBrowser.getSessionToken()
                        );

                        // 将 MediaController 与 Activity 关联
                        MediaControllerCompat.setMediaController(MainActivity.this, mediaController);

                        // 注册回调以接收媒体状态更新
                        mediaController.registerCallback(mediaControllerCallback);

                        // 检查初始extras
                        Bundle initialExtras = mediaController.getExtras();
                        if (initialExtras != null) {
                            Log.d(TAG, "Initial extras: " + initialExtras);
                            mediaControllerCallback.onExtrasChanged(initialExtras);
                        }

                        // 更新 UI 状态
                        runOnUiThread(() -> {
                            serviceStatus.setText("服务已连接");
                            updateMediaMetadata(mediaController.getMetadata());
                            updatePlaybackState(mediaController.getPlaybackState());
                            loadLyricsForCurrentSong(mediaController.getMetadata());
                        });

                        // 开始更新进度
                        handler.post(updateProgressRunnable);


                    } catch (Exception e) {
                        Log.e(TAG, "Failed to create MediaController", e);
                    }
                }

                @Override
                public void onConnectionSuspended() {
                    Log.d(TAG, "MediaBrowser connection suspended");
                    runOnUiThread(() -> serviceStatus.setText("服务连接已暂停"));
                }

                @Override
                public void onConnectionFailed() {
                    Log.e(TAG, "MediaBrowser connection failed");
                    runOnUiThread(() -> serviceStatus.setText("服务连接失败"));
                    Toast.makeText(MainActivity.this, "无法连接到媒体服务", Toast.LENGTH_SHORT).show();
                }
            };

    private final MediaControllerCompat.Callback mediaControllerCallback =
            new MediaControllerCompat.Callback() {
                @Override
                public void onPlaybackStateChanged(PlaybackStateCompat state) {
                    Log.d(TAG, "Playback state changed: " + state);
                    runOnUiThread(() -> updatePlaybackState(state));
                    // 更新歌词显示
                    if (state != null) {
                        lyricManager.updateLyric(state.getPosition());
                    }
                }

                @Override
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    Log.d(TAG, "Metadata changed: " + metadata);
                    runOnUiThread(() -> updateMediaMetadata(metadata));
                    // 加载对应歌曲的歌词
                    loadLyricsForCurrentSong(metadata);
                }

                @Override
                public void onExtrasChanged(Bundle extras) {
                    super.onExtrasChanged(extras);
                    Log.d(TAG, "Extras changed: " + extras);
                    if (extras.containsKey("service_info")) {
                        Log.d(TAG, "Service info: " + extras.getString("service_info"));
                    }
                    if (extras.containsKey("lyrics_supported")){
                        Log.d(TAG, "Lyrics supported: " + extras.getBoolean("lyrics_supported"));
                    }
                    if (extras.containsKey("is_playing")){
                        Log.d(TAG, "Is playing: " + extras.getBoolean("is_playing"));
                    }

                }
            };
    /**
     * 根据当前歌曲加载歌词
     * @param metadata 媒体元数据
     */
    private void loadLyricsForCurrentSong(MediaMetadataCompat metadata) {
        lyricManager.clearLyrics();
        String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
        Log.d(TAG, "Loading lyrics for: " + title);
        //这里可以根据歌曲名加载对应的歌词文件
        //loadLyricsFromExternalStorageBySongName( title);
        loadLyricsFromAssetsBySongName(title);
    }
    /**
     * 根据歌曲名加载对应的歌词文件
     * @param songName 歌曲名
     */
    private void loadLyricsFromAssetsBySongName(String songName) {
        if (songName == null || songName.isEmpty()) {
            lyricManager.clearLyrics();
            lyricsText.setText("暂无歌词");
            lyricsText.setGravity(Gravity.CENTER);
            return;
        }

        try {
            String fileName = songName + ".lrc"; // 或 .txt
            InputStream inputStream = getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder lyricsBuilder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                lyricsBuilder.append(line).append("\n");
            }

            reader.close();
            inputStream.close();
            lyricManager.parseLyrics(lyricsBuilder.toString());

        } catch (IOException e) {
            Log.e(TAG, "Error loading lyrics from assets: " + songName, e);
            lyricsText.setText("暂无歌词");
        }

    }
    private void loadLyricsFromExternalStorageBySongName(String songName) {
        try {
//            /storage/emulated/0/Download/music
            File lyricsDir = new File(Environment.getExternalStorageDirectory()+ "/Download/music");
            File lyricsFile = new File(lyricsDir, songName + ".lrc");
            Toast.makeText(this, "lyricsFile:"+lyricsFile, Toast.LENGTH_SHORT).show();
            if (lyricsFile.exists()) {
                StringBuilder lyricsBuilder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new FileReader(lyricsFile));
                String line;

                while ((line = reader.readLine()) != null) {
                    lyricsBuilder.append(line).append("\n");
                }

                reader.close();
                lyricManager.parseLyrics(lyricsBuilder.toString());
            }
        } catch (IOException e) {
            Log.d(TAG, "Error loading lyrics from external storage: " + songName);
        }
    }

    /**
     * 更新歌词显示
     * @param activeLineIndex 当前高亮行索引
     * @param lyrics 歌词列表
     */
    private void updateLyricsDisplay(int activeLineIndex, List<LyricManager.LyricLine> lyrics) {
        if (lyrics.isEmpty()) {
            lyricsText.setText("暂无歌词");
            lyricsText.setGravity(Gravity.CENTER);
            return;
        }

        StringBuilder displayText = getStringBuilder(activeLineIndex, lyrics);

        // 使用Html.fromHtml来支持颜色显示
        lyricsText.setText(android.text.Html.fromHtml(displayText.toString(), android.text.Html.FROM_HTML_MODE_LEGACY));
        //        Toast.makeText(this, displayText, Toast.LENGTH_SHORT).show();
        // 实现自动滚动效果
        if (activeLineIndex >= 0 && lyricsScrollView != null) {
            // 计算滚动位置，使当前行居中显示
            final int finalActiveLineIndex = activeLineIndex;
            lyricsText.post(() -> {
                // 获取布局信息
                android.text.Layout layout = lyricsText.getLayout();
                if (layout != null && finalActiveLineIndex < layout.getLineCount()) {
                    // 获取目标行的顶部和底部位置
                    int targetTop = layout.getLineTop(finalActiveLineIndex);
                    int targetBottom = layout.getLineBottom(finalActiveLineIndex);

                    // 计算目标行的中心位置
                    int targetCenter = (targetTop + targetBottom) / 2;

                    // 获取ScrollView的可见高度
                    int scrollViewHeight = lyricsScrollView.getHeight();

                    // 计算滚动位置，使目标行居中
                    int scrollTo = targetCenter - (scrollViewHeight / 2);

                    // 确保滚动位置不超出边界
                    int maxScroll = Math.max(0, lyricsText.getHeight() - scrollViewHeight);
                    scrollTo = Math.max(0, Math.min(scrollTo, maxScroll));

                    // 平滑滚动到目标位置
                    lyricsScrollView.smoothScrollTo(0, scrollTo);
                }
            });
        }
    }

    @NonNull
    private static StringBuilder getStringBuilder(int activeLineIndex, List<LyricManager.LyricLine> lyrics) {
        StringBuilder displayText = new StringBuilder();

        for (int i = 0; i < lyrics.size(); i++) {
            LyricManager.LyricLine line = lyrics.get(i);

            if (i == activeLineIndex) {
                // 当前行用不同颜色显示，统一使用<br/>换行
                displayText.append("<font color='#FF6B6B'><b>")
                        .append(line.text)
                        .append("</b></font><br/>");
            } else {
                displayText.append(line.text).append("<br/>");
            }
        }
        return displayText;
    }

    private void updatePlaybackState(PlaybackStateCompat state) {
        if (state == null) return;

        // 更新播放/暂停按钮
        switch (state.getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
                break;
            case PlaybackStateCompat.STATE_PAUSED:
            case PlaybackStateCompat.STATE_STOPPED:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                break;
        }

        // 更新进度条
        updateProgress();
    }
    private void updateMediaMetadata(MediaMetadataCompat metadata) {
        if (metadata == null) return;

        // 更新歌曲信息
        String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
        String artist = metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
        long duration = metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);

        songTitle.setText(title != null ? title : "未知歌曲");
        songArtist.setText(artist != null ? artist : "未知艺术家");
        totalTime.setText(formatTime(duration));
        progressSeekbar.setMax((int) duration);
    }

    //更新播放进度显示
    private void updateProgress() {
        if (mediaController != null) {
            PlaybackStateCompat state = mediaController.getPlaybackState();
            if (state != null) {
                long currentPosition = state.getPosition();
                currentTime.setText(formatTime(currentPosition));
                progressSeekbar.setProgress((int) currentPosition);
                // 更新歌词显示
                if (lyricManager != null) {
                    lyricManager.updateLyric(currentPosition);
                }
            }
        }
    }

    private String formatTime(long milliseconds) {
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Connecting to MediaBrowser");
        mediaBrowser.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "Disconnecting from MediaBrowser");

        // 停止更新进度
        handler.removeCallbacks(updateProgressRunnable);

        // 注销回调
        if (mediaController != null) {
            mediaController.unregisterCallback(mediaControllerCallback);
            mediaController = null;
        }

        mediaBrowser.disconnect();
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
    // 在onPause()中释放
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
